package com.fjb.service.user.impl;

import java.time.LocalDateTime;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjb.common.entity.HttpCode;
import com.fjb.common.entity.JsonResult;
import com.fjb.dto.LoginUserInfo;
import com.fjb.mapper.product.ProductInfoMapper;
import com.fjb.mapper.user.SysUserPraiseMapper;
import com.fjb.pojo.product.ProductInfo;
import com.fjb.pojo.user.SysUserPraise;
import com.fjb.service.user.SysUserPraiseService;

/**
 * <p>
 * 用户超赞 服务实现类
 * </p>
 *
 * @author hemiao
 * @since 2020-02-24
 */
@Service
public class SysUserPraiseServiceImpl extends ServiceImpl<SysUserPraiseMapper, SysUserPraise> implements SysUserPraiseService {
	
	@Autowired
	private SysUserPraiseMapper sysUserPraiseMapper;
	@Autowired
	private ProductInfoMapper productInfoMapper;
	
	@Transactional
	@Override
	public JsonResult<Boolean> addInfo(LoginUserInfo userInfo, Integer productId) {
		HttpCode httpCode = HttpCode.PARAM_VERIFICATION;
		Integer mainUserId = userInfo.getMainUserId();
		Integer userId = userInfo.getUserId();
		ProductInfo oldProduct = productInfoMapper.selectById(productId);
		if(oldProduct==null) {
			httpCode.setMsg("产品信息不存在");
			return new JsonResult<Boolean>(null, httpCode);
		}
		Integer userId2 = oldProduct.getUserId();
		if(userId.equals(userId2)) {
			httpCode.setMsg("不可超赞自己");	
			return new JsonResult<Boolean>(null, httpCode);
		}
			
		SysUserPraise uc = new SysUserPraise();
		uc.setMainUserId(mainUserId);
		uc.setUserId(userId);
		uc.setCreateUserId(userId);
		uc.setCreateTime(LocalDateTime.now());
		uc.setProductId(productId);
		int i = sysUserPraiseMapper.insert(uc);
		if(i==0) {
			httpCode.setMsg("添加超赞失败,请联系管理员");
			return new JsonResult<Boolean>(null, httpCode);
		}	
		productInfoMapper.updatePraiseCountAdd(productId);
		return new JsonResult<Boolean>(null, HttpCode.SUCCESS);
	}
	
	@Transactional
	@Override
	public JsonResult<Boolean> deleteInfo(Integer productId, Integer userId) {
		HttpCode httpCode = HttpCode.PARAM_VERIFICATION;
		QueryWrapper<SysUserPraise> queryWrapper = new QueryWrapper<SysUserPraise>();
		queryWrapper.eq("user_id", userId);
		queryWrapper.eq("product_id", productId);
		int i = sysUserPraiseMapper.delete(queryWrapper);
		if(i==0) {
			httpCode.setMsg("取消超赞失败,请联系管理员");
			return new JsonResult<Boolean>(null, httpCode);
		}	
		productInfoMapper.updatePraiseCountReduce(productId);
		return new JsonResult<Boolean>(null, HttpCode.SUCCESS);
	}

}
